import {
  Directive,
  EventEmitter,
  HostListener,
  Input,
  Output,
} from "@angular/core";
import { throttle } from "lodash";

export class MoveDrag {
  active: boolean = false;
  mousedownClientX: number = 0;
  mousedownClientY: number = 0;
  mouseupClientX: number = 0;
  mouseupClientY: number = 0;
}

export enum MoveTypes {
  Move = "Move",
  ResizeTop = "ResizeTop",
  ResizeRight = "ResizeRight",
  ResizeBottom = "ResizeBottom",
  ResizeLeft = "ResizeLeft",
  ResizeTopLeft = "ResizeTopLeft",
  ResizeTopRight = "ResizeTopRight",
  ResizeBottomLeft = "ResizeBottomLeft",
  ResizeBottomRight = "ResizeBottomRight",
}

@Directive({
  selector: "[appDrag]",
})
export class DragDirective {
  constructor() {}
  /** */
  data: MoveDrag = new MoveDrag();
  /**
   * 禁用
   */
  @Input() disabled: boolean = false;
  @Output() onDrag = new EventEmitter<MoveDrag>();
  @HostListener("mousedown", ["$event"])
  onMouseDown(event: any) {
    if (this.disabled) {
      return;
    }
    this.data.active = true;
    this.data.mousedownClientX = event.clientX;
    this.data.mousedownClientY = event.clientY;
  }
  /**监听页面焦点改变事件 */
  @HostListener("visibilitychange", ["$event"])
  onChange() {
    if (this.disabled || !this.data.active) {
      return;
    }
    this.data.active = false;
    throttle(() => this.onDrag.emit(this.data), 50);
  }
  /**监听document mousemove事件（防止鼠标移动太快超出元素） */
  @HostListener("document:mousemove", ["$event"])
  onMouseMove(event: any) {
    if (this.disabled || !this.data.active) {
      return;
    }

    this.data.mouseupClientX = event.clientX;
    this.data.mouseupClientY = event.clientY;
    this.onDrag.emit(this.data);
  }
  /**监听document mouseup事件（防止鼠标移动太快超出元素） */
  @HostListener("document:mouseup", ["$event"])
  onMouseUp(event: any) {
    if (this.disabled || !this.data.active) {
      return;
    }
    this.data.active = false;
    this.data.mouseupClientX = event.clientX;
    this.data.mouseupClientY = event.clientY;
    throttle(() => this.onDrag.emit(this.data), 50);
  }
}
